<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书管理系统 - 主页</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Noto Sans SC', Arial, sans-serif;
            background-color: #f8f9fa;
            color: #333;
            line-height: 1.6;
        }
        .header {
            background: linear-gradient(135deg, #2ecc71, #27ae60);
            color: white;
            padding: 1rem 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
        }
        .header h1 {
            margin: 0;
            font-size: 1.8rem;
            font-weight: 700;
        }
        .header .header-nav {
            display: flex;
            gap: 2rem;
            margin-left: auto;
        }
        .header .header-nav .nav-link {
            color: white;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s ease;
            padding: 0.5rem 1rem;
            border-radius: 4px;
        }
        .header .header-nav .nav-link:hover {
            background-color: rgba(255, 255, 255, 0.1);
            transform: translateY(-2px);
        }
        .user-info {
            display: flex;
            align-items: center;
            gap: 1.5rem;
            margin-left: 2rem;
        }
        .logout-btn {
            background-color: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 0.6rem 1.2rem;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
        }
        .logout-btn:hover {
            background-color: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
        }
        .main-content {
            max-width: 1400px;
            margin: 2rem auto;
            padding: 0 2rem;
        }
        .search-bar {
            display: flex;
            gap: 1rem;
            margin-bottom: 2rem;
            background: white;
            padding: 1.5rem;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        .search-input {
            flex: 1;
            padding: 1rem;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 1rem;
            transition: all 0.3s ease;
        }
        .search-input:focus {
            border-color: #2ecc71;
            outline: none;
            box-shadow: 0 0 0 3px rgba(46, 204, 113, 0.1);
        }
        .search-btn {
            padding: 1rem 2rem;
            background: linear-gradient(135deg, #2ecc71, #27ae60);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
            min-width: 120px;
        }
        .search-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(46, 204, 113, 0.2);
        }
        .book-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 2rem;
            padding: 1rem 0;
        }
        .book-card {
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            padding: 1.5rem;
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
        }
        .book-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
        }
        .book-image {
            width: 100%;
            height: 250px;
            object-fit: cover;
            border-radius: 8px;
            margin-bottom: 1rem;
        }
        .book-title {
            font-size: 1.3rem;
            margin-bottom: 0.8rem;
            color: #2c3e50;
            font-weight: 700;
        }
        .book-author {
            color: #34495e;
            margin-bottom: 0.8rem;
            font-weight: 500;
        }
        .book-info {
            color: #7f8c8d;
            font-size: 0.95rem;
            margin-bottom: 1rem;
        }
        .borrow-btn {
            width: 100%;
            padding: 0.8rem;
            background: linear-gradient(135deg, #2ecc71, #27ae60);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
            margin-top: auto;
        }
        .borrow-btn:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(46, 204, 113, 0.2);
        }
        .borrow-btn:disabled {
            background: #bdc3c7;
            cursor: not-allowed;
            transform: none;
        }
        .loading {
            display: none;
            text-align: center;
            padding: 2rem;
        }
        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #2ecc71;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .error-message {
            display: none;
            background-color: #ff6b6b;
            color: white;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            text-align: center;
        }
        @media (max-width: 768px) {
            .header {
                flex-direction: column;
                padding: 1rem;
            }
            .header-nav {
                margin: 1rem 0;
                flex-wrap: wrap;
                justify-content: center;
            }
            .user-info {
                margin: 1rem 0 0 0;
            }
            .main-content {
                padding: 0 1rem;
            }
            .search-bar {
                flex-direction: column;
            }
            .search-btn {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>图书管理系统</h1>
        <div class="header-nav">
            <a href="index.html" class="nav-link">浏览书籍</a>
            <a href="admin/addBook.html" class="nav-link">添加图书</a>
            <a href="profile.html" class="nav-link">修改个人信息</a>
            <a href="#" class="nav-link" id="mySubscriptionsBtn">我的订阅</a>
        </div>
        <div class="user-info">
            <span id="username"></span>
            <button class="logout-btn" onclick="logout()">退出登录</button>
        </div>
    </div>

    <div class="main-content">
        <div class="error-message" id="errorMessage"></div>
        <div class="search-bar">
            <input type="text" class="search-input" placeholder="搜索图书..." id="searchInput">
            <button class="search-btn" onclick="searchBooks()">搜索</button>
        </div>

        <div class="loading" id="loading">
            <div class="loading-spinner"></div>
        </div>

        <div class="book-list" id="bookList">
            <!-- 图书列表将通过JavaScript动态加载 -->
        </div>
    </div>

    <div id="subscriptionsModal" style="display:none; position:fixed; left:0; top:0; width:100vw; height:100vh; background:rgba(0,0,0,0.5); z-index:9999; align-items:center; justify-content:center;">
        <div style="background:#fff; padding:2rem; border-radius:12px; min-width:300px; max-width:90vw; box-shadow: 0 4px 24px rgba(0,0,0,0.1);">
            <h2 style="margin-bottom:1.5rem; color:#2c3e50;">我的订阅</h2>
            <div id="subscriptionsList"></div>
            <button onclick="closeModal()" style="margin-top:1.5rem; padding:0.8rem 1.5rem; background:#2ecc71; color:white; border:none; border-radius:6px; cursor:pointer; transition:all 0.3s ease;">关闭</button>
        </div>
    </div>

    <script>
        // 显示加载动画
        function showLoading() {
            document.getElementById('loading').style.display = 'block';
            document.getElementById('bookList').style.opacity = '0.5';
        }

        // 隐藏加载动画
        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
            document.getElementById('bookList').style.opacity = '1';
        }

        // 显示错误信息
        function showError(message) {
            const errorDiv = document.getElementById('errorMessage');
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
            setTimeout(() => {
                errorDiv.style.display = 'none';
            }, 5000);
        }

        // 检查登录状态
        function checkLogin() {
            showLoading();
            fetch('checkLogin')
                .then(response => response.json())
                .then(data => {
                    hideLoading();
                    if (!data.loggedIn) {
                        window.location.href = 'login.html';
                    } else {
                        document.getElementById('username').textContent = data.username;
                        if (data.role === 'admin') {
                            window.location.href = 'admin/dashboard.html';
                        } else {
                            loadBooks();
                        }
                    }
                })
                .catch(error => {
                    hideLoading();
                    showError('登录状态检查失败，请重试');
                    console.error('Error:', error);
                    window.location.href = 'login.html';
                });
        }

        // 加载图书列表
        async function loadBooks(searchTerm = '') {
            showLoading();
            let borrowedBookIds = [];
            try {
                const subRes = await fetch('/tushuguanli/mySubscriptions');
                if (subRes.ok) {
                    const subData = await subRes.json();
                    if (subData.success && subData.books) {
                        borrowedBookIds = subData.books.map(book => book.id);
                    }
                }
            } catch (e) {
                console.warn('获取订阅信息失败:', e);
            }

            let url = 'books';
            if (searchTerm) {
                url += `?q=${encodeURIComponent(searchTerm)}`;
            }
            try {
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const data = await response.json();

                const bookList = document.getElementById('bookList');
                bookList.innerHTML = '';
                if (data.length === 0) {
                    bookList.innerHTML = '<p style="text-align: center; padding: 2rem; color: #7f8c8d;">没有找到图书。</p>';
                    return;
                }
                data.forEach(book => {
                    const isBorrowed = borrowedBookIds.includes(book.id);
                    const bookCard = document.createElement('div');
                    bookCard.className = 'book-card';
                    bookCard.innerHTML = `
                        <img src="${book.image_path ? "getImage?name=" + book.image_path.substring(book.image_path.lastIndexOf('/') + 1) : 'images/default_book.png'}" 
                             alt="${book.title}" 
                             class="book-image"
                             onerror="this.src='images/default_book.png'">
                        <h3 class="book-title">${book.title}</h3>
                        <p class="book-author">作者：${book.author}</p>
                        <p class="book-info">ISBN：${book.isbn}</p>
                        <p class="book-info">可借数量：${book.available_copies}</p>
                        <button class="borrow-btn" 
                            onclick="borrowBook(${book.id})"
                            ${book.available_copies === 0 || isBorrowed ? 'disabled' : ''}>
                            ${isBorrowed ? '已借阅' : (book.available_copies === 0 ? '已无库存' : '借阅')}
                        </button>
                    `;
                    bookList.appendChild(bookCard);
                });
            } catch (error) {
                showError('加载图书列表失败，请重试');
                console.error('Error loading books:', error);
            } finally {
                hideLoading();
            }
        }

        // 搜索图书
        function searchBooks() {
            const searchTerm = document.getElementById('searchInput').value.trim();
            loadBooks(searchTerm);
        }

        // 借阅图书
        async function borrowBook(bookId) {
            showLoading();
            try {
                const response = await fetch(`/tushuguanli/borrowBook?bookId=${bookId}`, {
                    method: 'POST'
                });
                const data = await response.json();
                if (data.success) {
                    alert('借阅成功！');
                    loadBooks(document.getElementById('searchInput').value.trim());
                } else {
                    showError(data.message || '借阅失败，请重试');
                }
            } catch (error) {
                showError('借阅失败，请重试');
                console.error('Error borrowing book:', error);
            } finally {
                hideLoading();
            }
        }

        // 退出登录
        function logout() {
            fetch('logout', {
                method: 'POST'
            })
            .then(response => {
                window.location.href = 'login.html';
            })
            .catch(error => {
                showError('退出登录失败，请重试');
                console.error('Error:', error);
            });
        }

        // 显示订阅模态框
        document.getElementById('mySubscriptionsBtn').addEventListener('click', async function(e) {
            e.preventDefault();
            showLoading();
            try {
                const response = await fetch('/tushuguanli/mySubscriptions');
                const data = await response.json();
                if (data.success) {
                    const modal = document.getElementById('subscriptionsModal');
                    const list = document.getElementById('subscriptionsList');
                    list.innerHTML = '';
                    if (data.books && data.books.length > 0) {
                        data.books.forEach(book => {
                            list.innerHTML += `
                                <div style="padding:1rem; border-bottom:1px solid #eee;">
                                    <h3 style="margin-bottom:0.5rem;">${book.title}</h3>
                                    <p style="color:#666;">借阅时间：${book.dueDate ? new Date(book.dueDate).toLocaleDateString() : ''}</p>
                                    <button onclick="returnBook(${book.borrowId}, this, ${book.id})" style="margin-top:0.5rem; padding:0.5rem 1.2rem; background:#ff6b6b; color:white; border:none; border-radius:6px; cursor:pointer;">还书</button>
                                </div>
                            `;
                        });
                    } else {
                        list.innerHTML = '<p style="text-align:center; color:#666;">暂无借阅记录</p>';
                    }
                    modal.style.display = 'flex';
                } else {
                    showError('获取订阅信息失败');
                }
            } catch (error) {
                showError('获取订阅信息失败');
                console.error('Error:', error);
            } finally {
                hideLoading();
            }
        });

        // 还书功能
        function returnBook(borrowId, btn, bookId) {
            btn.disabled = true;
            fetch('/tushuguanli/cancelSubscription', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `borrowId=${encodeURIComponent(borrowId)}&bookId=${encodeURIComponent(bookId)}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    alert('还书成功');
                    // 重新加载订阅列表
                    document.getElementById('mySubscriptionsBtn').click();
                } else {
                    alert(data.message || '还书失败');
                    btn.disabled = false;
                }
            })
            .catch(() => {
                alert('网络错误');
                btn.disabled = false;
            });
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('subscriptionsModal').style.display = 'none';
        }

        // 页面加载完成后检查登录状态
        document.addEventListener('DOMContentLoaded', checkLogin);

        // 添加回车键搜索功能
        document.getElementById('searchInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                searchBooks();
            }
        });
    </script>
</body>
</html> 